package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.mybatis.entity.JobUser;
import com.xxl.job.executor.mybatis.service.JobUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.xxl.job.core.handler.IJobHandler.SUCCESS;


/**
 * @author: 吴多强
 * @description: 分片批量插入
 */
@Component
public class ShardingBatchInsert {
    private static Logger logger = LoggerFactory.getLogger(ShardingBatchInsert.class);
    @Resource
    private JobUserService jobUserService;

    @XxlJob("ShardingBatchInsert")
    public ReturnT<String> shardingJobHandler(String param) throws Exception {
        // 当前分片序号
        int index = XxlJobContext.getXxlJobContext().getShardIndex() + 1;
        // 总分片数
        int total = XxlJobContext.getXxlJobContext().getShardTotal();
        // 总的分片任务
        int all = Integer.parseInt(param);
        // 平均分片个数
        int avg = all / total;
        logger.info("当前分片序号" + index + " 总分片数" + total + "总的分片任务" + all + "平均分片个数" + avg);
        // 开始数
        int start = index == 1 ? 1 : (index - 1) * avg + 1;
        // 结束数
        int end = index * avg;
        logger.info("开始" + start + "结束" + end);
        List<JobUser> jobUsers = new ArrayList<>();
        return getStringReturnT(start, end, jobUsers, jobUserService);
    }

    static ReturnT<String> getStringReturnT(int start, int end, List<JobUser> jobUsers, JobUserService jobUserService) {
        addJobUser(start, end, jobUsers);
        long startTime = System.currentTimeMillis() / 1000;
        jobUserService.insertBatch(jobUsers);
        long endTime = System.currentTimeMillis() / 1000;
        logger.info("耗时" + (endTime - startTime) + "秒");
        return SUCCESS;
    }

    static void addJobUser(int start, int end, List<JobUser> jobUsers) {
        for (int i = start; i <= end; i++) {
            // 测试数据
            JobUser jobUser = new JobUser();
            jobUser.setId(i);
            jobUser.setUsername("123");
            jobUser.setPassword("456");
            jobUser.setPhone("789");
            jobUser.setMail("000");
            jobUsers.add(jobUser);
        }
    }
}
